Add option to treat strings starting with $ as JSONPath

Andrew Cantino 10 years ago
parent
commit
63a42fff3c
2 changed files with 20 additions and 9 deletions
  1. 12 8
      lib/utils.rb
  2. 8 1
      spec/lib/utils_spec.rb

+ 12 - 8
lib/utils.rb

@@ -21,20 +21,24 @@ module Utils
21 21
     end
22 22
   end
23 23
 
24
-  def self.interpolate_jsonpaths(value, data)
25
-    value.gsub(/<[^>]+>/).each { |jsonpath|
26
-      Utils.values_at(data, jsonpath[1..-2]).first.to_s
27
-    }
24
+  def self.interpolate_jsonpaths(value, data, options = {})
25
+    if options[:leading_dollarsign_is_jsonpath] && value[0] == '$'
26
+      Utils.values_at(data, value).first.to_s
27
+    else
28
+      value.gsub(/<[^>]+>/).each { |jsonpath|
29
+        Utils.values_at(data, jsonpath[1..-2]).first.to_s
30
+      }
31
+    end
28 32
   end
29 33
 
30
-  def self.recursively_interpolate_jsonpaths(struct, data)
34
+  def self.recursively_interpolate_jsonpaths(struct, data, options = {})
31 35
     case struct
32 36
       when Hash
33
-        struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data); memo }
37
+        struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data, options); memo }
34 38
       when Array
35
-        struct.map {|elem| recursively_interpolate_jsonpaths(elem, data) }
39
+        struct.map {|elem| recursively_interpolate_jsonpaths(elem, data, options) }
36 40
       when String
37
-        interpolate_jsonpaths(struct, data)
41
+        interpolate_jsonpaths(struct, data, options)
38 42
       else
39 43
         struct
40 44
     end

+ 8 - 1
spec/lib/utils_spec.rb

@@ -28,8 +28,15 @@ describe Utils do
28 28
   end
29 29
 
30 30
   describe "#interpolate_jsonpaths" do
31
+    let(:payload) { { :there => { :world => "WORLD" }, :works => "should work" } }
32
+
31 33
     it "interpolates jsonpath expressions between matching <>'s" do
32
-      Utils.interpolate_jsonpaths("hello <$.there.world> this <escape works>", { :there => { :world => "WORLD" }, :works => "should work" }).should == "hello WORLD this should+work"
34
+      Utils.interpolate_jsonpaths("hello <$.there.world> this <escape works>", payload).should == "hello WORLD this should+work"
35
+    end
36
+
37
+    it "optionally supports treating values that start with '$' as raw JSONPath" do
38
+      Utils.interpolate_jsonpaths("$.there.world", payload).should == "$.there.world"
39
+      Utils.interpolate_jsonpaths("$.there.world", payload, :leading_dollarsign_is_jsonpath => true).should == "WORLD"
33 40
     end
34 41
   end
35 42